package no.weather.weatherProxy.wsKlima;

import java.util.LinkedList;
import java.util.List;

import no.weather.WeatherType;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class WeatherTypesHandler extends DefaultHandler {
	private String code = null;
	private String description = null;
	private Boolean includeNotProvidingStations;
	private Boolean isInTypeItem = false;
	private String lastLocalName = null;
	private String name = null;
	private String toDate = null;
	private List<WeatherType> types = new LinkedList<WeatherType>();
	private String unit = null;

	public WeatherTypesHandler() {
		super();
	}

	public WeatherTypesHandler(Boolean includeNotProvidingStations) {
		super();
		this.includeNotProvidingStations = includeNotProvidingStations;
	}

	/**
	 * Gets be called on the following structure: <tag>characters</tag>
	 */
	@Override
	public void characters(char ch[], int start, int length) {
		String valueS = new String(ch, start, length);

		if (valueS.equals("\n")) {
			;
		} else if (isInTypeItem)
			if (lastLocalName.equals("unit")) {
				unit = valueS;
			} else if (lastLocalName.equals("name")) {
				name = valueS;
			} else if (lastLocalName.equals("description")) {
				description = valueS;
			} else if (lastLocalName.equals("elemCode")) {
				code = valueS;
			} else if (lastLocalName.equals("todate")) {
				toDate = valueS;
			} else if (lastLocalName.equals("fromdate")) {
			}

	}

	@Override
	public void endDocument() throws SAXException {
	}

	/**
	 * Gets be called on closing tags like: </tag>
	 */
	@Override
	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		if (localName.equals("item")) {
			isInTypeItem = false;
			newType();

		}

	}

	public List<WeatherType> getResult() {
		return types;
	}

	/**
	 * Add the reed data to collection
	 */
	private void newType() {

		if (!includeNotProvidingStations) {
			if (toDate != null) {
				reset();
				return;
			}
		}

		types.add(new WeatherType(code, description, name, unit));
		reset();
	}

	/**
	 * Set all data to null
	 */
	private void reset() {
		code = null;
		description = null;
		unit = null;
		name = null;
		toDate = null;
	}

	@Override
	public void startDocument() throws SAXException {
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) {
		if (localName.equals("item")) {
			String type = attributes.getValue(0);
			if (type.equals("ns3:no_met_metdata_ElementProperties")) {
				isInTypeItem = true;
			}
		} else {
			lastLocalName = localName;
		}
	}

}
